<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect,NFlex
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '仪器管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const data = reactive({
  CityData: [],
  config:[],
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '仪器',
  initForm: {},
  doCreate: api.createDevice,
  doUpdate: api.updateDevice,
  doDelete: api.deleteDevice,
  refresh: () => $table.value?.handlerefresh(),
})

onMounted(() => {
  $table.value?.handleSearch()
  api.getConfig().then((res) => {
    data.config = res.data
  })
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '仪器名称',
    key: 'title',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
      fixed: 'left',
  },
  {
    title: '设备地址',
    key: 'address',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
      fixed: 'left',
  },
  {
    title: '设备编号',
    key: 'device_number',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
      fixed: 'left',
  },
    {
    title: '供应商',
    key: 'supplier',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
      fixed: 'left',
  },
  {
    title: '禁用',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        checkedValue: 1,
        uncheckedValue: 0,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该用户吗?'),
          }
        ),
      ]
    },
  },
]

async function handleUpdateDisable(row) {
  if (!row.id) return
  row.status = row.status ? 0 : 1
  try {
    await api.updateDevice(row)
    $message?.success(row.status ? '已禁用该仪器' : '已取消禁用该仪器')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.status === 0 ? 1 : 0
  } finally {
    row.publishing = false
  }
}

</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="仪器列表">
        <template #action>
          <NButton  type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建仪器
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getDeviceList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="仪器名称" :label-width="90">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="请输入仪器名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <NFormItem label="仪器名称" path="title">
              <NInput v-model:value="modalForm.title" clearable placeholder="请输入仪器名称" />
            </NFormItem>
            <NFormItem label="设备地址" path="address">
              <NInput v-model:value="modalForm.address" clearable placeholder="请输入设备地址" />
            </NFormItem>
            <NFormItem label="设备编号" path="device_number">
              <NInput v-model:value="modalForm.device_number" clearable placeholder="请输入设备编号" />
            </NFormItem>
            <NFormItem label="供应商" path="supplier">
              <NSelect
                    v-model:value="modalForm.supplier"
                    :options="data.config.gongying"
                    placeholder="供应商"
                    filterable
                    label-field="name"
                    value-field="name"
                    style="width: 100%"
                  />
            </NFormItem>
            <NFormItem label="禁用" path="status">
              <NSwitch
                v-model:value="modalForm.status"
                :checked-value="false"
                :unchecked-value="true"
                :default-value="true"
              />
            </NFormItem>

          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
